package com.gxa.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxa.common.base.RespResult;
import com.gxa.common.constants.DateRangeConstants;
import com.gxa.common.util.TimeSlotUtil;
import com.gxa.modules.dto.OrderFileVo;
import com.gxa.modules.dto.OrderInsertDTO;
import com.gxa.modules.dto.OrderPageDTO;
import com.gxa.modules.entity.*;
import com.gxa.modules.mapper.*;
import com.gxa.modules.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Create with IntelliJ IDEA.
 * Description:
 * User: ZY
 * Date: 2023-03-23
 * Time: 16:26
 */
@Service
@Slf4j
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    @Autowired
    OrderStateMapper orderStateMapper;

    @Autowired
    OrderShipmentMapper orderShipmentMapper;

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    CustomerMapper customerMapper;

    /**
     * 简单查询
     * @param currentPagecurrentPage
     * @param pageSize
     * @param timeSlot
     * @param condition
     * @return
     */

    @Override
    public RespResult findOrderListByCondition(Integer currentPagecurrentPage, Integer pageSize, String timeSlot, String condition) {

        Page<CrmOrder> OrderPage=null;

        Map<String ,Object> map = new HashMap<>();

        Date startTime=null;

        Date endTime=null;

        if(DateRangeConstants.NEW_TODAY.equals(timeSlot)){
            //当天新增
            startTime = TimeSlotUtil.getTimesmorning();

            endTime = TimeSlotUtil.getTimesnight();

        }else if(DateRangeConstants.NEW_THIS_WEEK.equals(timeSlot)){
            //当周新增
            startTime = TimeSlotUtil.getTimesWeekmorning();

            endTime = TimeSlotUtil.getTimesWeeknight();

        }else if(DateRangeConstants.NEW_THIS_MONTH.equals(timeSlot)){
            //当月新增
            startTime = TimeSlotUtil.getTimesMonthmorning();

            endTime = TimeSlotUtil.getTimesMonthnight();

        }else{
            startTime = TimeSlotUtil.getTimesmorning();

            endTime = TimeSlotUtil.getTimesnight();


        }

        OrderPage = orderMapper.findOrderList(new Page<CrmOrder>(currentPagecurrentPage, pageSize),startTime,endTime,condition,null);

        List<Map> orderList = new ArrayList<>();

        for(int i=0;i<OrderPage.getRecords().size();i++){
            if(OrderPage.getRecords().get(i)!=null){

                CrmOrder crmOrder = OrderPage.getRecords().get(i);
                orderList.add(getOrder(crmOrder));

            }


        }
        return RespResult.success(orderList);
    }







    /**
     * 根据天、周、月查看订单
     * @param currentPagecurrentPage
     * @param pageSize
     * @param timeSlot
     * @return
     */
    @Override
    public RespResult findOrderList(Integer currentPagecurrentPage, Integer pageSize, String timeSlot) {

        List<Map> orderList = new ArrayList<>();

        IPage<CrmOrder> page = new Page<>(currentPagecurrentPage,pageSize);//参数一：当前页，参数二：每页记录数

        //按天、周、月排序
        LambdaQueryWrapper<CrmOrder> queryWrapper = new LambdaQueryWrapper<>();

        if(DateRangeConstants.NEW_TODAY.equals(timeSlot)){
            //当天新增
            queryWrapper.ge(CrmOrder::getEntryTime, TimeSlotUtil.getTimesmorning())
                    .le(CrmOrder::getEntryTime, TimeSlotUtil.getTimesnight())
                    .orderByDesc(CrmOrder::getEntryTime);

        }else if(DateRangeConstants.NEW_THIS_WEEK.equals(timeSlot)){
            //当周新增
            queryWrapper.ge(CrmOrder::getEntryTime, TimeSlotUtil.getTimesWeekmorning())
                    .le(CrmOrder::getEntryTime, TimeSlotUtil.getTimesWeeknight())
                    .orderByDesc(CrmOrder::getEntryTime);

        }else if(DateRangeConstants.NEW_THIS_MONTH.equals(timeSlot)){
            //当月新增
            queryWrapper.ge(CrmOrder::getEntryTime, TimeSlotUtil.getTimesMonthmorning())
                    .le(CrmOrder::getEntryTime, TimeSlotUtil.getTimesMonthnight())
                    .orderByDesc(CrmOrder::getEntryTime);

        }else{

            queryWrapper.orderByDesc(CrmOrder::getEntryTime);

        }


        IPage<CrmOrder> userIPage = orderMapper.selectPage(page, queryWrapper);


        //根据订单id查询订单全部信息并封装返回
        for(int i=0;i<userIPage.getRecords().size();i++){
            if(userIPage.getRecords().get(i)!=null){

                CrmOrder crmOrder = userIPage.getRecords().get(i);
                orderList.add(getOrder(crmOrder));

            }


        }
        return RespResult.success(orderList);
    }








    /**
     * 查询用户名下所有订单
     * @param customerId
     * @return
     */
    @Override
    public RespResult findOrderListByCustomer(Integer customerId) {

        List<Map> orderList = new ArrayList<>();

        LambdaQueryWrapper<CrmOrder> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(CrmOrder::getCustomerId,customerId).orderByDesc(CrmOrder::getEntryTime);

        List<CrmOrder> crmOrders = orderMapper.selectList(queryWrapper);
        //根据订单id查询订单全部信息并封装返回
        for(int i=0;i<crmOrders.size();i++){
            if(crmOrders.get(i)!=null){

                CrmOrder crmOrder = crmOrders.get(i);
                orderList.add(getOrder(crmOrder));

            }


        }

        return RespResult.success(orderList);
    }







    /**
     * 根据id查询订单信息
     * @param orderId
     * @return
     */

    @Override
    public RespResult findOrderListById(Integer orderId) {

        CrmOrder crmOrder = orderMapper.selectById(orderId);


        return RespResult.success(getOrder(crmOrder));
    }







    /**
     * 高级查询
     * @param orderPageDTO
     * @return
     */
    @Override
    public RespResult findOrderListByOrderConditions(OrderPageDTO orderPageDTO) {
        Page<CrmOrder> OrderPage=null;

        Map<String ,Object> map = new HashMap<>();

        Date startTime=null;

        Date endTime=null;

        if(DateRangeConstants.NEW_TODAY.equals(orderPageDTO.getTimeSlot())){
            //当天新增
            startTime = TimeSlotUtil.getTimesmorning();

            endTime = TimeSlotUtil.getTimesnight();

        }else if(DateRangeConstants.NEW_THIS_WEEK.equals(orderPageDTO.getTimeSlot())){
            //当周新增
            startTime = TimeSlotUtil.getTimesWeekmorning();

            endTime = TimeSlotUtil.getTimesWeeknight();

        }else if(DateRangeConstants.NEW_THIS_MONTH.equals(orderPageDTO.getTimeSlot())){
            //当月新增
            startTime = TimeSlotUtil.getTimesMonthmorning();

            endTime = TimeSlotUtil.getTimesMonthnight();

        }else{
            startTime = TimeSlotUtil.getTimesmorning();

            endTime = TimeSlotUtil.getTimesnight();


        }
        OrderPage = orderMapper.findOrderList(new Page<CrmOrder>(orderPageDTO.getCurrentPage(), orderPageDTO.getPageSize()),startTime,endTime,null,orderPageDTO);

        List<Map> orderList = new ArrayList<>();

        for(int i=0;i<OrderPage.getRecords().size();i++){
            if(OrderPage.getRecords().get(i)!=null){

                CrmOrder crmOrder = OrderPage.getRecords().get(i);
                orderList.add(getOrder(crmOrder));

            }


        }
        return RespResult.success(orderList);
    }





    /**
     * 更改订单状态
     * @param crmOrderState
     * @return
     */
    @Override
    public RespResult updateOrderStateById(CrmOrderState crmOrderState) {
        int i = orderStateMapper.updateById(crmOrderState);

        if(i>0){
            return RespResult.success();
        }else{
            return  RespResult.error("修改数据失败");
        }

    }





    /**
     * 增加订单商品
     * @param crmOrderGoods
     * @return
     */
    @Override
    public RespResult addOrderGoodsById(CrmOrderGoods crmOrderGoods) {

        crmOrderGoods.setEntryTime(new Date());

        int i = orderGoodsMapper.insert(crmOrderGoods);

        if(i>0){
            return RespResult.success();
        }else {
            return RespResult.error("增加失败");
        }
    }







    /**
     * 修改订单商品
     * @param crmOrderGoods
     * @return
     */
    @Override
    public RespResult updateOrderGoodsById(CrmOrderGoods crmOrderGoods) {

        int i = orderGoodsMapper.updateById(crmOrderGoods);

        if(i>0){
            return RespResult.success();
        }else {
            return RespResult.error("修改失败");
        }
    }






    /**
     * 新增到款
     *
     * @param orderId
     * @param received
     * @return
     */
    @Override
    public RespResult updatedReceiverById(Integer orderId, BigDecimal received) {

        BigDecimal re = orderMapper.selectById(orderId).getReceived().add(received);

        CrmOrder crmOrder = new CrmOrder();

        crmOrder.setReceived(re);

        int i = orderMapper.updateById(crmOrder);

        if(i>0){
            return RespResult.success();
        }else {
            return RespResult.error("修改失败");
        }

    }






    /**
     *增加订单
     *
     * @return
     */
    @Override
    public RespResult addOrder(OrderInsertDTO orderInsertDTO) {

        //生成订单信息
        //生成订单状态
        CrmOrderState crmOrderState = new CrmOrderState();
        crmOrderState.setOrderStatus(0);

        orderStateMapper.insert(crmOrderState);

        //生成发货状态
        CrmOrderShipment crmOrderShipment = new CrmOrderShipment();
        crmOrderShipment.setShipmentStatus(0);

//        orderStateMapper.insert(crmOrderShipment);

        orderInsertDTO.setOrderStatusId(crmOrderState.getOrderStateId());
        orderInsertDTO.setEntryTime(new Date());

        //插入订单
        int insert = orderMapper.insert(orderInsertDTO);

        //插入商品
        if(orderInsertDTO.getCrmOrderGoodsList()!=null) {
            for (int i = 0; i < orderInsertDTO.getCrmOrderGoodsList().size(); i++) {

                CrmOrderGoods crmOrderGoods = orderInsertDTO.getCrmOrderGoodsList().get(i);
                crmOrderGoods.setOrderId(orderInsertDTO.getOrderId());
                orderGoodsMapper.insert(crmOrderGoods);
            }
        }



        return RespResult.success(insert) ;
    }





    /**
     * 修改订单
     *
     * @return
     */
    @Override
    public RespResult updateOrderById(OrderInsertDTO orderInsertDTO) {
        return null;
    }
//导出接口
    @Override
    public List<OrderFileVo> listPage(Map<String, Object> queryCondition, Integer pageNo, Integer pageSize) {
        Integer offset = (pageNo - 1) * pageSize;
        Integer rows = pageSize;
        queryCondition.put("offset",offset);
        queryCondition.put("rows",rows);

            return orderMapper.showAllByPage(queryCondition);
    }


    /**
     * 封装订单信息返回
     * @param crmOrder
     * @return
     */
    public Map getOrder(CrmOrder crmOrder){
        Map<String,Object> map = new HashMap<>();
        //订单客户信息获取
        CrmCustomer crmCustomer = customerMapper.selectById(crmOrder.getCustomerId());


        //订单商品获取
        LambdaQueryWrapper<CrmOrderGoods> queryWrapper1 = new LambdaQueryWrapper<>();

        queryWrapper1.eq(CrmOrderGoods::getOrderId, crmOrder.getOrderId()).orderByDesc(CrmOrderGoods::getEntryTime);

        List<CrmOrderGoods> crmOrderGoods = orderGoodsMapper.selectList(queryWrapper1);
        //计算商品总价
        BigDecimal totalMoney = new BigDecimal("0.0");
        for(int i=0;i<crmOrderGoods.size();i++){

            //根据商品id查询商品及商品价格

            CrmOrderGoods goods = crmOrderGoods.get(i);
            totalMoney = totalMoney.add((goods.getDiscount()).multiply(new BigDecimal(goods.getQuantity())));
        }
        orderStateMapper.selectList(null);

        //订单状态获取
        CrmOrderState crmOrderState = orderStateMapper.selectById(crmOrder.getOrderStatusId());

        //发货状态获取
        CrmOrderShipment crmOrderShipment = orderShipmentMapper.selectById(crmOrder.getShipmentStatusId());

        //获取业务员
        Employee employee = employeeMapper.selectById(crmOrder.getEmployeeId());


        map.put("orderId",crmOrder.getOrderId());

        map.put("customer",crmCustomer);

        map.put("orderNo",crmOrder.getOrderNo());

        map.put("orderDate",crmOrder.getOrderDate());

        map.put("PresentationDate",crmOrder.getPresentationDate());

        map.put("totalMoney",totalMoney);

        map.put("received",crmOrder.getReceived());

        map.put("debt",totalMoney.subtract(crmOrder.getReceived()!=null?crmOrder.getReceived():new BigDecimal("0.0")));

        map.put("orderStatus",crmOrderState);

        map.put("ShipmentStute",crmOrderShipment);

        map.put("remarks",crmOrder.getOrderRemarks());

        map.put("salesman",employee);

        map.put("entryTime",crmOrder.getEntryTime());

        map.put("enclosure","enclosure");

        map.put("goods",crmOrderGoods);

        return map;
    }
}
